package com.jgp.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jgp.common.BaseContext;
import com.jgp.common.R;
import com.jgp.entity.AddressBook;
import com.jgp.service.AddressBookSerice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {
    @Autowired
    private AddressBookSerice addressBookSerice;
    /**
     * 新增
     */
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrentId());
        log.info("addressbooj:{}",addressBook);
        addressBookSerice.save(addressBook);
        return R.success(addressBook);
    }
    /**
     * 设置默认地址
     */
    @PutMapping("default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook){
        log.info("addressword:{}",addressBook);
        LambdaUpdateWrapper<AddressBook> alambdaWrapper = new LambdaUpdateWrapper<>();
        alambdaWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        alambdaWrapper.set(AddressBook::getDetail,0);
        addressBookSerice.update(alambdaWrapper);
        addressBook.setIsDefault(1);
        addressBookSerice.updateById(addressBook);
        return  R.success(addressBook);

    }
    /**
     * 查询默认地址
     */
    @GetMapping("default")
    public R<AddressBook> getdefault(){
        LambdaQueryWrapper<AddressBook> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        objectLambdaQueryWrapper.eq(AddressBook::getDetail,1);
        AddressBook one = addressBookSerice.getOne(objectLambdaQueryWrapper);
        if(one==null){
            return R.error("没有找到对象");
        }else{
            return R.success(one);
        }

    }
    /**
     * 查询指定用户的全部地址
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrentId());
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(addressBook!=null,AddressBook::getUserId,addressBook.getUserId());
        addressBookLambdaQueryWrapper.orderByDesc(AddressBook::getUpdateTime);
        return R.success(addressBookSerice.list(addressBookLambdaQueryWrapper));

    }
}
